package main

import (
	"flag"
	"fmt"
	"gitee.com/larry_dev/goban"
	"gitee.com/larry_dev/gogtp"
	"runtime"
	"strings"
)

var (
	move   int
	shell  string
	game   int
	afters string
	sgf    string
)

func init() {
	flag.StringVar(&shell, "shell", "./normal.sh", "脚本")
	flag.IntVar(&move, "move", 300, "落子手数")
	flag.IntVar(&game, "game", 1, "对弈数")
	flag.StringVar(&afters, "afters", "", "执行命令,多个命令以;分开")
	flag.StringVar(&sgf, "sgf", "", "落子")
	flag.Parse()
}
func main() {
	client, err := gogtp.NewConnectionByStr(shell)
	if err != nil {
		panic(err)
	}
	gtp, err := gogtp.NewGTPCommand(client)
	if err != nil {
		panic(err)
	}
	//gtp.ShowLog(true)
	gtp.LogHook(func(event, data string) {
		fmt.Println(event,data)
	})
	if sgf != "" {

		kifu := goban.ParseSgf(sgf)
		kifu.EachNode(func(n *goban.Node, move int) bool {
			for _, v := range n.Steup {
				_, _ = gtp.Move(v.GetColor(), goban.CoorToBoardNode(v.X, v.Y, kifu.Size))
			}
			fmt.Println("落子")
			if n.GetColor() != "" {
				_, _ = gtp.Move(n.GetColor(), goban.CoorToBoardNode(n.X, n.Y, kifu.Size))
			}
			return false
		})
		result, err := gtp.GenMove("B")
		if err != nil {
			panic(err)
		}
		fmt.Println(result)
		return
	}
	commands := strings.Split(afters,";")
	for _, v := range commands {
		if len(v)>0{
			_, _ = gtp.SendCMD(v)
		}
	}
	for g := 1; g <= game; g++ {
		fmt.Println("对局数", g)

		color := "B"
		_, _ = gtp.ClearBoard()
		for i := 1; i <= move; i++ {

			fmt.Println("Move before:", runtime.NumGoroutine(), "，当前开始对局数为：", g, "当前手数：", i)
			result, err := gtp.GenMove(color)
			if err != nil {
				panic(err)
			}
			fmt.Println(result.Result)
			if gtp.Version() >= 0.17 {
				outputs, _ := goban.ParseLZOutputV17(result.ErrOut, 19, 3)
				if len(outputs) == 0 {
					fmt.Printf("%v\n", result)
					panic("分支为空")
				} else {
					fmt.Println("分支数量为：", len(outputs))
				}
			} else {
				outputs, _ := goban.ParseLZOutput(result.ErrOut, 19, 3)
				if len(outputs) == 0 {
					fmt.Printf("%v\n", result)
					panic("分支为空")
				} else {
					fmt.Println("分支数量为：", len(outputs))
				}
			}
			if color == "B" {
				color = "W"
			} else {
				color = "B"
			}
			fmt.Println("Move after:", runtime.NumGoroutine())
		}

		fmt.Println("After Game End:", runtime.NumGoroutine())
	}
	client.Close()

}
